//201902104003邵潇漩
package bysj.controller.basic;

import bysj.domain.Student;
import bysj.service.*;
import bysj.domain.Teacher;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import util.Condition;
import util.ControllerHelper;
import util.JSONUtil;
import util.Pagination;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

/**
 * @author shaoxiaoxuann@163.com
 * @version 1.0  11-03-2020
 * School Controller
 */
@Slf4j
@WebServlet("/student.ctl")
public class StudentController extends HttpServlet {
    /**
     * GET, http://localhost:8080/school.ctl?id=1, 查询id=1的学院
     * GET, http://localhost:8080/school.ctl, 查询所有的学院
     * 把一个或所有学院对象响应到前端
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        //设置响应字符编码为UTF-8
        //  response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null) {
            respMessage_jsonObj.put("message","未收到请求信息！");
            response.getWriter().println(respMessage_jsonObj);
            return;
        }
        //从JSONObject对象中读取键“id”的值（Java Object对象），req_jsonObj可能是{"id":1}
        Object id_obj = req_jsonObj.get("id");
        try {
            //如果id_Obj != null, 说明请求数据有id键，是请求某个教师对象
            if (id_obj != null) {
                int id_int = Integer.parseInt(id_obj.toString());
                responseStudent(id_int, response);
                log.info("id=" + id_int);
            } else {
                //请求中包含条件和分页信息，需要响应多个教师对象
                if(req_jsonObj.get("teacherId")!=null) {
                    Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
                    responseStudents(response, Integer.parseInt(req_jsonObj.get("teacherId").toString()), pagination);
                }else{
                    Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
                    List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
                    this.responseStudents(response, pagination, conditionList);
                }
            }
        }catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试（要用log4j代替）
            log.error("数据库操作异常:"+e);
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试（要用log4j代替）
            log.error("网络异常:"+e);
        }
    }
    //响应一个学院对象
    private void responseStudent(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //根据id查找学院
        Student student = StudentService.getInstance().find(id);
        String student_json = JSON.toJSONString(student);
        //响应school_json到前端
        response.getWriter().println(student_json);
    }
    //响应所有学院对象
    private void responseStudents(HttpServletResponse response,Pagination pagination,List<Condition> conditionList)
            throws ServletException, IOException, SQLException {
        //获得满足条件的所有院系
        Collection<Student> students = StudentService.getInstance().findAll(conditionList,pagination);
        String student_json = JSON.toJSONString(students, SerializerFeature.DisableCircularReferenceDetect);
        JSONObject response_json = new JSONObject();
        response_json.put("totalNum" ,pagination.getTotalNum());
        response_json.put("data",student_json);
        //响应department_json 到前端
        response.getWriter().println(response_json);
    }
    private void responseStudents(HttpServletResponse response,int teacherId,Pagination pagination)
            throws ServletException, IOException, SQLException {
        Teacher teacher= TeacherService.getInstance().find(teacherId);
        //获得满足条件的所有院系
        Collection<Student> students = StudentService.getInstance().findAll(teacher,pagination);
        String student_json = JSON.toJSONString(students, SerializerFeature.DisableCircularReferenceDetect);
        JSONObject response_json = new JSONObject();
        response_json.put("totalNum" ,pagination.getTotalNum());
        response_json.put("data",student_json);
        //响应department_json 到前端
        response.getWriter().println(response_json);
    }
    /**
     * POST, http://localhost:8080/studentt.ctl, 增加学生
     * 增加一个学生对象：将来自前端请求的JSON对象，增加到数据库表中
     *
     * @param request  请求对象
     * @param response 响应对象
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置请求字符编码为UTF-8
        //request.setCharacterEncoding("UTF-8");
        //根据request对象，获得代表参数的JSON字串
        String student_json = JSONUtil.getJSON(request);
        JSONObject req_jsonObj = JSON.parseObject(student_json);
        //将JSON字串解析为Department对象
        Student studentToAdd = JSON.parseObject(student_json, Student.class);
        //设置响应字符编码为UTF-8
        //  response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //在数据库表中增加Department对象
        try {
            Object studentClassId_obj = req_jsonObj.get("studentClass_id");
            int studentClassId_int = Integer.parseInt(studentClassId_obj.toString());
            studentToAdd.setStudentClass(StudentClassService.getInstance().find(studentClassId_int));
            Object teacherId_obj = req_jsonObj.get("teacherId");
            int teacherId_int = Integer.parseInt(teacherId_obj.toString());
            studentToAdd.setSupervisor(TeacherService.getInstance().find(teacherId_int));

            StudentService.getInstance().add(studentToAdd);
            message.put("message", "增加成功");
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            log.error("数据库操作异常:"+e);
        } catch (Exception e) {
            message.put("message", "网络异常");
            log.error("网络异常:"+e);
        }
        //响应message到前端
        response.getWriter().println(message);
    }
    /**
     * PUT, http://localhost:8080/school.ctl, 修改学院
     *
     * 修改一个学院对象：将来自前端请求的JSON对象，更新数据库表中相同id的记录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置请求字符编码为UTF-8
        //request.setCharacterEncoding("UTF-8");
        String student_json = JSONUtil.getJSON(request);
        JSONObject req_jsonObj = JSON.parseObject(student_json);
        //将JSON字串解析为School对象
        Student studentToAdd = JSON.parseObject(student_json, Student.class);
        //设置响应字符编码为UTF-8
        //  response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //到数据库表修改School对象对应的记录
        try {
            Object studentClassId_obj = req_jsonObj.get("studentClass_id");
            int studentClassId_int = Integer.parseInt(studentClassId_obj.toString());
            studentToAdd.setStudentClass(StudentClassService.getInstance().find(studentClassId_int));
            Object teacherId_obj = req_jsonObj.get("teacherId");
            int teacherId_int = Integer.parseInt(teacherId_obj.toString());
            studentToAdd.setSupervisor(TeacherService.getInstance().find(teacherId_int));
            StudentService.getInstance().update(studentToAdd);
            message.put("message", "修改成功");
        }catch (SQLException e){
            message.put("message", "数据库操作异常");
            log.error("数据库操作异常:"+e);
        }catch(Exception e){
            message.put("message", "网络异常");
            log.error("网络异常:"+e);
        }
        //响应message到前端
        response.getWriter().println(message);
    }
    /**
     * DELETE, http://localhost:8080/department.ctl?id=1, 删除id=1的系
     * 删除一个系对象：根据来自前端请求的id，删除数据库表中id的对应记录
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //从JSONObject对象中读取键“id”的值（Java Object对象），req_jsonObj可能是{"id":1}
        Object id_obj = req_jsonObj.get("id");
        int id_int = Integer.parseInt(id_obj.toString());
        //设置响应字符编码为UTF-8
        //  response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //到数据库表中删除对应的系
        try {
            StudentService.getInstance().delete(id_int);
            message.put("message", "删除成功");
        }catch (SQLException e) {
            message.put("message", "数据库操作异常");
            log.error("数据库操作异常:"+e);
        }catch (Exception e) {
            message.put("message", "网络异常");
            log.error("网络异常:"+e);
        }
        //响应message到前端
        response.getWriter().println(message);
    }
    //得到一个Logger对象，**.class是将要加入日志的类加进入
   // private final Logger logger = Logger.getLogger(StudentController.class);
}
